********************************************************************
* This file generates the estimates reported in Table 4, Column 1. *
********************************************************************

*************************
* 0 Set path to files *
*************************
clear all
capture log close
set more off
set trace off
cd $main_directory

//Set predetermined values:
sca scale=10
//Load the data and the commands used in the estimation of the spatial demand model
use "Data_Belgium\Generated_data\baseline_demand_dataset.dta"
qui do "Command_files\spatial_demand_Q.do"

//Calculate the total demand on the market
qui su Q if common==1
sca sumQ=r(sum)
sca di sumQ
//Calculate the total population on the market
bysort market_ID:  gen dup_market = cond(_N==1,0,_n)
qui su population if dup_market<2
sca sumPopulation=r(sum)
sca di sumPopulation
//Calculate total potential demand per capita as 10 times larger than the current value.
scalar gamma=scale*sumQ/sumPopulation
sca di gamma
//Calculate the market size (i.e. number of possible transactions)
gen market_size=gamma*population

//Define the product for which demand will be estimated (in this case total transactions).
gen firm_demand=Q 
drop if firm_demand==.
drop if firm_demand<=0

//Generate a unique numeric identifier for the market.
sort market_ID
egen market_ID_num = group(market_ID)
// Controls
global controls_utility distance lnNotPerOff start_not LDE Perc_Young Perc_Elderly log_income popdens
global controls_total firm_ID firm_demand market_ID_num market_size $controls_utility
//Estimate the demand for all transactions: this is column 1 of Table 4.
spatialdemand_logQ $controls_total
//Store the estimates for later use.
parmest,  saving("Estimates\spatial_demand_Q", replace)
est store spatial_Q
mata: betas_Q=st_matrix("e(b)")'
mata: mata matsave "Estimates\betas_Q" betas_Q, replace

//Industry nesting parameter (mu_1^k)
nlcom 1/(1+exp(-_b[nest]))
mat list e(b)
